﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IRepository.LY;
using DFGK.IService.LY;
using DFGK_WMS.Model.Models.LyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service.LY
{
    public class PurchaseService : BaseService, IPurchaseService
    {
        private readonly IPurchaseRepository _purchaseRepository;
        private readonly IUnitOfWork _unitOfWork;
        public PurchaseService(IMapper mapper, IPurchaseRepository purchaseRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            _purchaseRepository = purchaseRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddOrModefiyPurchase(Purchase model, out string errorMsg)
        {
            errorMsg = string.Empty;
            if (model.Id > 0)
            {
                _purchaseRepository.UpdEntity(model);
            }
            else
            {
                _purchaseRepository.AddEntity(model);

            }
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelPurchase(long purchaseId)
        {
            var Quote = _purchaseRepository.QueryEntityById(purchaseId);
            if (Quote == null)
            {
                return false;
            }
            _purchaseRepository.DelEntity(Quote);
            return _unitOfWork.SaveChangesEntity();
        }

        public Purchase? GetPurchase(long purchaseId)
        {
            return _purchaseRepository.QueryEntityById(purchaseId);
        }

        public List<Purchase> GetPurchaseData(DateTime? startDate, DateTime? endDate, out int totalCount, int pageIndex = 1, int pageSize = 15)
        {
            var list = _purchaseRepository.GetEntityAlls();
            
            if (startDate.HasValue)
            {
                list = list.Where(r => r.PurchaseDate >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                list = list.Where(r => r.PurchaseDate <= endDate.Value);
            }
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(d => d.CreateDate);
            return list.ToList();
        }
    }
}
